package uit.minito.timduongxebuyt;

import java.util.ArrayList;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import uit.minito.model.MyData;
import uit.minito.model.RouterModel;
import uit.minito.views.CustomZoomControls;
import uit.minito.views.OnCustomZoomControlsListener;
import uit.minito.views.RouterInfoViewer;
import uit.minito.views.Utility;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class RouterViewActivity extends FragmentActivity implements OnCustomZoomControlsListener{

	GoogleMap myMapView;
	LatLng p;
	LatLng geoPoint;
	RouterInfoViewer infoViewer;
	LatLng HCM = new LatLng(10.770959, 106.699384);
	CustomZoomControls customZoomControl;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_router);
		// StrictMode.ThreadPolicy policy = new
		// StrictMode.ThreadPolicy.Builder().permitAll().build();
		// StrictMode.setThreadPolicy(policy);  
		
		SupportMapFragment mapFrag= (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapRouter);
		myMapView = mapFrag.getMap();
		
		//myMapView = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
		myMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(HCM, 14));
		myMapView.getUiSettings().setZoomControlsEnabled(false);
		infoViewer = (RouterInfoViewer)findViewById(R.id.routerInfoViewer);
		customZoomControl = (CustomZoomControls) findViewById(R.id.zoomControl);
		customZoomControl.delegate = this;

		new GetArrayRouterTask().execute(StaticVariables.serverURL + "/RouterPage");
		
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		customZoomControl.show();
		switch (ev.getAction()) {
		
		case MotionEvent.ACTION_UP:
			customZoomControl.runTimer();  
			break;
		}
		return super.dispatchTouchEvent(ev);
	}

	class GetArrayRouterTask extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... uri) {

			String jsonRouterID = Utility.getJsonFromURL(uri[0]);

			return jsonRouterID;
		}  
  
		@Override  
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			ArrayList<String> arrayRouter = new ArrayList<String>();

			try {
				JSONArray array = new JSONArray(result);
				for (int i = 0; i < array.length(); i++) {

					String routerID = array.getJSONObject(i).getString("RouterID").substring(4);
					String routerName = array.getJSONObject(i).getString("RouterName");
					

					
					arrayRouter.add(routerID + " - " + routerName);  
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Spinner sp = (Spinner) findViewById(R.id.spRouter);
			ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
					android.R.layout.simple_spinner_item, arrayRouter);

			sp.setAdapter(spinnerArrayAdapter);  

			
			
			sp.setOnItemSelectedListener(new OnItemSelectedListener() {
			
				public void onItemSelected(AdapterView<?> arg0, View arg1, int index, long arg3) {
					// TODO Auto-generated method stub
					
					TextView tv = (TextView) arg1;
					String text = (String) tv.getText();

					Toast.makeText(getApplicationContext(), tv.getText(), Toast.LENGTH_SHORT).show();
					new DrawRouterTask().execute(StaticVariables.serverURL + "/RouterPage?routerID=RHCM"
							+ text.substring(0, 3) + "&direction=" + 0);
				
				}

				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub

				}
			});
		}
	}

	class DrawRouterTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... uri) {

			return Utility.getJsonFromURL(uri[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			if (result == null || result.equals("")) {
				Toast.makeText(getApplicationContext(), "Không có dữ liệu", Toast.LENGTH_SHORT).show();
				return;
			}

			myMapView.clear();

			JSONArray allResultarr = new JSONArray();
			try {
				allResultarr = new JSONArray(result);
				JSONObject routeModel = allResultarr.getJSONObject(0).getJSONObject("routerModel");
				RouterModel iRouter = new RouterModel();  
				iRouter.setRouterID(routeModel.getString("RouterID").substring(4));
				iRouter.setRouterName(routeModel.getString("RouterName").replace("\n", ""));  
				iRouter.setTotalDistance(routeModel.getDouble("TotalDistance"));
				iRouter.setNumberOfRouter(routeModel.getString("NumberOfRouter"));
				iRouter.setTotalTimeMin(routeModel.getInt("TotalTimeMin"));
				iRouter.setTotalTImeMax(routeModel.getInt("TotalTImeMax"));
				iRouter.setWaitingTimeMin(routeModel.getInt("WaitingTimeMin"));
				iRouter.setWaitingTImeMax(routeModel.getInt("WaitingTImeMax"));
				iRouter.setAvaliableHours(routeModel.getString("AvaliableHours"));
				iRouter.setIsBargain(routeModel.getInt("IsBargain"));  
				iRouter.setInChargeUnit(routeModel.getString("InChargeUnit"));
				
				infoViewer.updateInfo(iRouter.toList());
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Vector<MyData> dataResult = new Vector<MyData>();

			try {

				for (int i = 0; i < allResultarr.length(); i++) {
					MyData md;
					JSONObject jo = allResultarr.getJSONObject(i);
					if (!jo.has("address")) {
						md = new MyData(jo.getDouble("lat"), jo.getDouble("lng"));
					} else {
						md = new MyData(jo.getDouble("lat"), jo.getDouble("lng"), jo.getString("routerID"),
								jo.getString("address"));
					}

					dataResult.add(md);
				}

			} catch (Exception e) {

			}
			
			
			
			
			// Draw Router
			Vector<LatLng> arrPoint = new Vector<LatLng>();
		
			for (int i = 0; i < dataResult.size(); i++) {
				arrPoint.add(dataResult.get(i).getLatLng());
			}

			DrawPathOverlay dpo = new DrawPathOverlay(myMapView, getApplicationContext(), arrPoint, Color.RED);
			dpo.draw();
		
			// Draw Station Marker:
			for (int i = 0; i < dataResult.size(); i++) {
				if (dataResult.get(i).getAddress() != null && dataResult.get(i).getAddress() != "") {

					myMapView.addMarker(new MarkerOptions()
							.position(new LatLng(dataResult.get(i).getLat(), dataResult.get(i).getLng()))
							.icon(BitmapDescriptorFactory.fromResource(R.drawable.locationicon))
							.title("Vị trí trạm dừng:").snippet(dataResult.get(i).getAddress()));
				}
			}
			
			myMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(dataResult.firstElement().getLatLng(), 14));
			
		}
	}

	public void onPressZoomingIn() {
		// TODO Auto-generated method stub
		myMapView.animateCamera(CameraUpdateFactory.zoomIn());
	}

	public void onPressZoomingOut() {
		// TODO Auto-generated method stub
		myMapView.animateCamera(CameraUpdateFactory.zoomOut()); 
	}


}
